package com.mjk.manager.magicapi.core.utils;


import com.mjk.manager.magicapi.core.core.config.Constants;
import com.mjk.manager.magicapi.core.core.context.MagicUser;
import com.mjk.manager.magicapi.core.core.servlet.MagicHttpServletRequest;
import com.mjk.manager.magicapi.core.core.servlet.MagicRequestContextHolder;

import java.security.Principal;
import java.util.Optional;

/**
 * Web相关工具类
 *
 * @author mxd
 */
public class WebUtils {

    public static MagicRequestContextHolder magicRequestContextHolder;

    public static String currentUserName() {
        MagicUser user = magicRequestContextHolder.getCurrentUser();
        if (null != user) {
            return user.getUsername();
        }
        Optional<MagicHttpServletRequest> request = Optional.ofNullable(magicRequestContextHolder.getRequest());
        return request.map(r -> (MagicUser) r.getAttribute(Constants.ATTRIBUTE_MAGIC_USER))
                .map(MagicUser::getUsername)
                .orElseGet(() -> request.map(MagicHttpServletRequest::getUserPrincipal)
                        .map(Principal::getName)
                        .orElse(null)
                );
    }

}
